import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { CopyRecordEntity } from '@entity/jx3/copyRecord.entity';
import {
  ListCopyRecordDTO,
  CreateCopyRecordDTO,
  UpdateCopyRecordDTO,
} from '@dto/jx3/copyRecord.dto';
import { resBuild } from '@utils/resBuild';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { getOperator, getTimeFormat, getUUID } from '@utils';
import { JwtService } from '@midwayjs/jwt';
import { UserService } from '@service/system/user.service';
import { ListUserDTO } from '@dto/system/user.dto';
import { DropsService } from '@service/jx3/drops.service';

@Provide()
export class CopyRecordService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(CopyRecordEntity)
  CopyRecordEntity: Repository<CopyRecordEntity>;

  @Inject()
  jwtService: JwtService;

  @Inject()
  userService: UserService;

  @Inject()
  DropsService: DropsService;

  async getUserId() {
    // 从请求头或请求参数中获取token
    const token = this.ctx.headers.authorization?.split(' ')[1]; // 假设token在Authorization头中，格式为Bearer <token>
    const decoded: any = await this.jwtService.verify(token, {
      complete: true,
    });
    return decoded.payload.userId;
  }

  // 列表
  async list(queryParams: ListCopyRecordDTO) {
    const queryBuilder = this.CopyRecordEntity.createQueryBuilder('entity');

    // 添加按创建时间排序，默认降序（最新的在前）
    queryBuilder.orderBy('entity.createTime', 'DESC');

    if (queryParams.pageNum && queryParams.pageSize) {
      queryBuilder
        .skip((queryParams.pageNum - 1) * queryParams.pageSize)
        .take(queryParams.pageSize);
    }

    const [rows, total] = await queryBuilder.getManyAndCount();
    return resBuild.list(rows, total);
  }

  // 我的副本列表
  async myList(queryParams: ListCopyRecordDTO) {
    const queryBuilder = this.CopyRecordEntity.createQueryBuilder('entity');

    // 添加按创建时间排序，默认降序（最新的在前）
    queryBuilder.orderBy('entity.createTime', 'DESC');
    queryBuilder.andWhere('entity.userId = :userId', {
      userId: await this.getUserId(),
    });

    if (queryParams.pageNum && queryParams.pageSize) {
      queryBuilder
        .skip((queryParams.pageNum - 1) * queryParams.pageSize)
        .take(queryParams.pageSize);
    }

    const [rows, total] = await queryBuilder.getManyAndCount();
    for (let i of rows) {
      let { rows } = await this.DropsService.list({
        recordId: i.id,
      });
      i.list = rows;
    }
    return resBuild.list(rows, total);
  }

  // 统计周
  async countWeek(queryParams: ListCopyRecordDTO) {
    const queryBuilder = this.CopyRecordEntity.createQueryBuilder('entity');

    // 计算本周的时间范围
    const today = new Date();
    const dayOfWeek = today.getDay() || 7; // 转换为周一为1，周日为7
    const startOfWeek = new Date(today);
    startOfWeek.setDate(today.getDate() - (dayOfWeek - 1));
    startOfWeek.setHours(0, 0, 0, 0); // 本周一 00:00:00

    const endOfWeek = new Date(today);
    endOfWeek.setDate(today.getDate() + (7 - dayOfWeek));
    endOfWeek.setHours(23, 59, 59, 999); // 本周日 23:59:59.999

    // 添加本周时间范围条件
    queryBuilder.andWhere('entity.createTime BETWEEN :start AND :end', {
      start: startOfWeek,
      end: endOfWeek,
    });

    queryBuilder.andWhere('entity.userId = :userId', {
      userId: await this.getUserId(),
    });

    // 统计 copyWages 和 copyUse 字段的总和
    queryBuilder.select([
      'SUM(entity.copyWages) as totalCopyWages',
      'SUM(entity.copyUse) as totalCopyUse',
      'SUM(entity.copyXuanJing) as totalXuanJing',
      'SUM(entity.copySpecial) as totalSpecial',
      'COUNT(entity.id) as recordCount', // 统计记录条数，假设主键为id
    ]);

    // 执行聚合查询，获取统计结果
    const stats = await queryBuilder.getRawOne();

    // 处理可能的null值（当没有数据时）
    const result = {
      totalCopyWages: stats?.totalCopyWages || 0,
      totalCopyUse: stats?.totalCopyUse || 0,
      totalXuanJing: stats?.totalXuanJing || 0,
      totalSpecial: stats?.totalSpecial || 0,
      recordCount: stats?.recordCount || 0,
    };

    // 返回统计结果
    return resBuild.data(result);
  }

  // 统计周
  async countTotal(queryParams: ListCopyRecordDTO) {
    const queryBuilder = this.CopyRecordEntity.createQueryBuilder('entity');

    // 从请求头或请求参数中获取token
    queryBuilder.andWhere('entity.userId = :userId', {
      userId: await this.getUserId(),
    });

    // 统计 copyWages 和 copyUse 字段的总和
    queryBuilder.select([
      'SUM(entity.copyWages) as totalCopyWages',
      'SUM(entity.copyUse) as totalCopyUse',
      'SUM(entity.copyXuanJing) as totalXuanJing',
      'SUM(entity.copySpecial) as totalSpecial',
      'COUNT(entity.id) as recordCount', // 统计记录条数，假设主键为id
    ]);

    // 执行聚合查询，获取统计结果
    const stats = await queryBuilder.getRawOne();

    // 处理可能的null值（当没有数据时）
    const result = {
      totalCopyWages: stats?.totalCopyWages || 0,
      totalCopyUse: stats?.totalCopyUse || 0,
      totalXuanJing: stats?.totalXuanJing || 0,
      totalSpecial: stats?.totalSpecial || 0,
      recordCount: stats?.recordCount || 0,
    };

    // 返回统计结果
    return resBuild.data(result);
  }

  // 统计周
  async countMonth(queryParams: ListCopyRecordDTO) {
    const queryBuilder = this.CopyRecordEntity.createQueryBuilder('entity');

    // 计算本月的时间范围
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth(); // 月份从0开始计数（0-11）

    // 本月第一天 00:00:00
    const startOfMonth = new Date(year, month, 1);
    startOfMonth.setHours(0, 0, 0, 0);

    // 本月最后一天 23:59:59.999
    // 下个月第一天的前一天就是本月最后一天
    const endOfMonth = new Date(year, month + 1, 0);
    endOfMonth.setHours(23, 59, 59, 999);

    // 添加本月时间范围条件
    queryBuilder.andWhere('entity.createTime BETWEEN :start AND :end', {
      start: startOfMonth,
      end: endOfMonth,
    });
    // 从请求头或请求参数中获取token
    queryBuilder.andWhere('entity.userId = :userId', {
      userId: await this.getUserId(),
    });

    // 统计各个字段的总和
    queryBuilder.select([
      'SUM(entity.copyWages) as totalCopyWages',
      'SUM(entity.copyUse) as totalCopyUse',
      'SUM(entity.copyXuanJing) as totalXuanJing',
      'SUM(entity.copySpecial) as totalSpecial',
      'COUNT(entity.id) as recordCount', // 统计记录条数，假设主键为id
    ]);

    // 执行聚合查询，获取统计结果
    const stats = await queryBuilder.getRawOne();

    // 处理可能的null值（当没有数据时）
    const result = {
      totalCopyWages: stats?.totalCopyWages || 0,
      totalCopyUse: stats?.totalCopyUse || 0,
      totalXuanJing: stats?.totalXuanJing || 0,
      totalSpecial: stats?.totalSpecial || 0,
      recordCount: stats?.recordCount || 0,
    };

    // 返回统计结果
    return resBuild.data(result);
  }

  // 添加
  async create(CopyRecord: CreateCopyRecordDTO) {
    // 新增
    CopyRecord.userId = await this.getUserId();
    CopyRecord.id = getUUID();
    const myEntity = this.CopyRecordEntity.create(CopyRecord);
    const { userInfo }: { userInfo: ListUserDTO } =
      await this.userService.userInfo();
    myEntity.setCreateBy(userInfo.nickName);
    myEntity.setUpdateBy(userInfo.nickName);
    myEntity.setCreateTime(getTimeFormat());
    myEntity.setUpdateTime(getTimeFormat());

    for (let i of CopyRecord.copyDrops) {
      i.copyName = CopyRecord.copyName;
      i.recordId = CopyRecord.id;
      await this.DropsService.create(i);
    }
    await this.CopyRecordEntity.save(myEntity);
    return resBuild.success();
  }

  // 删除
  async delete(id: string) {
    const ids = id.split(',').map(id => Number(id));
    await this.CopyRecordEntity.delete(ids);
    return resBuild.success();
  }

  // 修改
  async update(CopyRecord: UpdateCopyRecordDTO) {
    const myEntity = this.CopyRecordEntity.create(CopyRecord);
    myEntity.setUpdateBy(getOperator(this.ctx));
    myEntity.setUpdateTime(getTimeFormat());
    await this.CopyRecordEntity.save(myEntity);
    return resBuild.success();
  }

  // 详情
  async detail(id: string) {
    const detailInfo = await this.CopyRecordEntity.findOneBy({
      id,
    });
    return resBuild.data(detailInfo);
  }
}
